package com.ch.web.interceptor;

import com.ch.web.annotation.IgnoreLogin;
import com.ch.web.enums.UserEnumCollection;
import com.ch.web.redis.UserMapCache;
import com.ch.web.service.XyTokenService;
import com.ch.web.utils.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    XyTokenService xyTokenService;

    @Autowired
    UserMapCache userMapCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        if (request.getRequestURI().startsWith("/res")){
            return true;
        }
        IgnoreLogin methodAnnotation = null;
        if (handler instanceof HandlerMethod) {
            methodAnnotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreLogin.class);
        }
        if (null != methodAnnotation) {
            return true;
        }
        String token = request.getHeader("token");
        if (null == token) {
            checkTokenFail(response);
            return false;
        }
        if (!userMapCache.isHaveToken(token)) {
            checkTokenFail(response);
            return false;
        }
        if (userMapCache.isExpire(token)) {
            new ObjectMapper().writeValue(response.getWriter(), R.error(UserEnumCollection.USER_EXPIRE_TOKEN.getCode(),UserEnumCollection.USER_EXPIRE_TOKEN.getMessage()));
            return false;
        }
        return true;
    }

    private void checkTokenFail(HttpServletResponse response) throws IOException {
        R error = R.error(UserEnumCollection.USER_EMPTY_TOKEN.getCode(), UserEnumCollection.USER_EMPTY_TOKEN.getMessage());
        new ObjectMapper().writeValue(response.getWriter(), error);
    }
}
